from Agent import Agent
import mechanize, re, tempfile, time, logging, sys
from bettybox.Document import Document


class CESUAgent(Agent):
  
  def __init__(self, user, password):
    Agent.__init__(self, "EDF Bleu Ciel")
    self.__user = user
    self.__password = password
    
  def Connect(self):
    print "Connect to CESU"
    self.__br = self.getBrowser()
    self.__br.open('http://www.cesu.urssaf.fr/cesweb/home.jsp')
    self.__br.follow_link(url_regex='loginempl')
    self.__br.select_form('Connexion')
    self.__br["abonLogin"] = self.__user
    self.__br["abonPasswd"] = self.__password    
    self.__br.submit()
    print "Connection OK"
  
  def Collect(self):
    self.Connect()
    return self.__collectAttestationFiscale()
    
  def __collectAttestationFiscale(self):
    print "Collect <Attestations Fiscales>"
    resp = self.__br.follow_link(url_regex='atfiempl')
    # Parse all years for the form
    years = map(lambda x : x.group(1), re.finditer('<option value="(\d+)"', resp.read()))
    print "Found years: ", years
    for year in years:
      self.__br.select_form('formulaire')
      self.__br['annee'] = [year]
      self.__br.submit()
      yield self.__getAttestationFiscale(year)
      self.__br.back()
      
  def __getAttestationFiscale(self, year):
    resp = self.__br.follow_link(url_regex='attestationfiscaleempl.pdf\?annee=' + year)
    attachment = tempfile.NamedTemporaryFile(delete=False)
    attachment.write(resp.read())
    attachment.close()
    print "Wrote temp <attestation fiscale> in: ", attachment.name
    doc = Document()
    doc.title = 'CESU - Attestation fiscale annee ' + year
    doc.attachment = attachment.name
    doc.tags += [ 'cesu', 'urssaf', 'attestation employeur' ]
    return doc
    
    
if __name__ == '__main__':
  #logger = logging.getLogger("mechanize")
  #logger.addHandler(logging.StreamHandler(sys.stdout))
  #logger.setLevel(logging.DEBUG)
  
  agent = CESUAgent('GUILLAUME.FOURNIER', 'xxxxxxxx')
  for doc in agent.Collect():
    print doc.title
  #agent.Connect()
